import { ref, computed } from 'vue'
import { useVideoStore } from '../renderer/stores/videoStore'
import { VideoService } from '../services/videoService'
import { PLAYER } from '../constants/player'
import { getFileName, addSafeFileProtocol } from '../utils/file'
import { handleError, createErrorMessage } from '../utils/error'
import { debounce } from '../utils/performance'

export function useVideoSearch() {
  const videoStore = useVideoStore()
  const searchTags = ref([])
  const currentInput = ref('')
  const inputRef = ref(null)

  const hasSearchResults = computed(() => {
    return searchTags.value.length > 0 && groupedResults.value.length > 0
  })

  const groupedResults = computed(() => {
    if (!searchTags.value.length) return []
    
    const groups = {}
    const queries = searchTags.value.map(tag => tag.toLowerCase())
    
    videoStore.allTags.forEach(tag => {
      if (!groups[tag.video_path]) {
        groups[tag.video_path] = {
          path: tag.video_path,
          name: getFileName(tag.video_path),
          tags: new Set()
        }
      }
      groups[tag.video_path].tags.add(tag.name.toLowerCase())
    })

    return Object.values(groups).filter(video => {
      const tagSet = video.tags
      return queries.every(query => 
        Array.from(tagSet).some(tagName => tagName.includes(query))
      )
    })
  })

  const handleInput = debounce(() => {
    videoStore.searchTags(searchTags.value.join(' '))
  }, PLAYER.TIMELINE.THROTTLE)

  const addTag = () => {
    const value = currentInput.value.trim()
    if (value && !searchTags.value.includes(value)) {
      searchTags.value.push(value)
      currentInput.value = ''
      handleInput()
    }
  }

  const removeTag = (index) => {
    searchTags.value.splice(index, 1)
    handleInput()
  }

  const handleBackspace = (event) => {
    if (currentInput.value === '' && searchTags.value.length > 0) {
      event.preventDefault()
      searchTags.value.pop()
      handleInput()
    }
  }

  const openVideo = async (video) => {
    videoStore.currentVideo = {
      path: addSafeFileProtocol(video.path),
      name: video.name,
      originalPath: video.path
    }
    await videoStore.loadTags(video.path)
    await videoStore.updateVideoInfo(video.path)
    videoStore.setCurrentPage('player')
  }

  return {
    searchTags,
    currentInput,
    inputRef,
    hasSearchResults,
    groupedResults,
    handleInput,
    addTag,
    removeTag,
    handleBackspace,
    openVideo
  }
} 